package com.sxds.wn.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.sxds.wn.model.JsonPage;
import com.sxds.wn.service.IService;
import com.sxds.wn.service.Request;
import com.sxds.wn.service.Response;

/**
 * Description: <p>处理java对象转换为json脚本对象</p>
 * Content Desc:<p>处理java对象转换为json脚本对象<p>
 * @author Andy
 * @version 1.0
 */

public class JsonServlet extends BaseServlet {
	
	private static final long serialVersionUID = 12340203L;
	
	/**
	 * Constructor of the object.
	 */
	public JsonServlet() {
		super();
	}
	
	/* (non-Javadoc)
	 * @see com.sxds.wn.servlet.BaseServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String serviceBean = request.getParameter("serviceBean");
		IService service = (IService)this.getApplicationContext().getBean(serviceBean);
		//处理类型,1--处理返回tree对象，2--处理返回json的分页格式
		String processType = request.getParameter("processType");
		//默认处理是返回json tree格式对象
		if( processType==null || "".equals(processType) ) processType = "1";
		Request andyRequst = new Request(request);
		Response andyResponse = null;
		try{
			andyResponse = service.process(andyRequst);
			//处理返回结果,下级
			if( andyResponse.getStackTraceException()!=null ){
				//处理请求发生异常,处理异常
				this.processExceptionWithJson(request, response, andyResponse.getStackTraceException(), andyResponse);
			}else{
				processResponse(request, response, andyRequst, andyResponse);
			}
		}catch(Exception ex){
			log.error("处理请求错误：",ex);
			//处理异常处理
			this.processExceptionWithJson(request, response, ex, andyResponse);
		}
	}

	@Override
	protected void processResponse(HttpServletRequest request,
			HttpServletResponse response, Request andyRequst,
			Response andyResponse) throws ServletException, IOException {
		String processType = request.getParameter("processType");
		//默认处理是返回json tree格式对象
		if( processType==null || "".equals(processType) ) processType = "1";
		//处理返回结果
		if( "1".equals(processType) ){
			this.processJsonTree(request, response, andyResponse);
		}else{
			this.processJsonGrid(request, response, andyResponse);
		}
	}
	
	/**
	 * 处理返回json tree数据格式
	 * @param request
	 * @param response
	 * @param andyResponse
	 * @throws ServletException
	 * @throws IOException
	 */
	private void processJsonTree(HttpServletRequest request, HttpServletResponse response,
								 Response andyResponse)throws ServletException, IOException {
		if( andyResponse.isOk() ){
			String charEncode = request.getCharacterEncoding();
			Map attributes = andyResponse.getPageAttributes();
			List treeList = null;
			//查找List对象的数据
			if( !attributes.isEmpty() ){
				Iterator it = attributes.keySet().iterator();
				while( it.hasNext() ){
					String key = (String)it.next();
					Object value = attributes.get(key);
					if( value instanceof List ){
						treeList = (List)value;
					}
				}
			}
			response.setContentType("text/html");
			response.setCharacterEncoding(charEncode);
			PrintWriter out = response.getWriter();
			if( treeList==null || treeList.size()==0 ){
				out.write("[]");
			}else{
				JSONArray jsonTree = JSONArray.fromObject(treeList);
				jsonTree.write(out);
			}
			out.flush();
			out.close();
		}
	}

	/**
	 * 处理返回json grid 数据格式
	 * @param request
	 * @param response
	 * @param andyResponse
	 * @throws ServletException
	 * @throws IOException
	 */
	private void processJsonGrid(HttpServletRequest request, HttpServletResponse response,
			 Response andyResponse)throws ServletException, IOException {
		if( andyResponse.isOk() ){
			Map attributes = andyResponse.getPageAttributes();
			JsonPage jsonPage = null;
			//查找List对象的数据
			if( !attributes.isEmpty() ){
				Iterator it = attributes.keySet().iterator();
				while( it.hasNext() ){
					String key = (String)it.next();
					Object value = attributes.get(key);
					if( value instanceof JsonPage ){
						jsonPage = (JsonPage)value;
					}
				}
			}
			response.setContentType("text/html");
			response.setCharacterEncoding(request.getCharacterEncoding());
			PrintWriter out = response.getWriter();
			if( jsonPage==null ){
				out.write("{totalCount:0,list:{}}");
			}else{
				JSONObject jsonObject = JSONObject.fromObject(jsonPage);
				jsonObject.write(out);
			}
			out.flush();
			out.close();
		}
	}
	
	/**
	 * 处理Ext的ComboBox类型需要的数据类型
	 * @param request
	 * @param response
	 * @param andyResponse
	 * @throws ServletException
	 * @throws IOException
	 */
	private void processJsonComboBox(HttpServletRequest request, HttpServletResponse response,
			 Response andyResponse)throws ServletException, IOException {
		if( andyResponse.isOk() ){
			Map attributes = andyResponse.getPageAttributes();
			List comboBoxList = null;
			//查找List对象的数据
			if( !attributes.isEmpty() ){
				Iterator it = attributes.keySet().iterator();
				while( it.hasNext() ){
					String key = (String)it.next();
					Object value = attributes.get(key);
					if( value instanceof List ){
						comboBoxList = (List)value;
					}
				}
			}
			response.setContentType("text/html");
			response.setCharacterEncoding(request.getCharacterEncoding());
			PrintWriter out = response.getWriter();
			if( comboBoxList==null || comboBoxList.size()==0 ){
				out.write("{}");
			}else{
				JSONArray jsonTree = JSONArray.fromObject(comboBoxList);
				jsonTree.write(out);
			}
			out.flush();
			out.close();
		}
	}
	
}
